/*
 *
 * Copyright (c) 2023 - future
 * @author fzh
 * @email e_341877120_mail@163.com
 * @link https://mvnrepository.com/search?q=io.github.xrfzh.cn
 *
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package cn.xrfzh.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 对象序列化工具（Redis存储数据量超过10w字节推荐使用，提升存储效率）
 *
 * @author fzh
 */
public class XrSerializeUtil {

	/**
	 * 对象序列化
	 * @param object 对象
	 * @return byte[] 字节流
	 */
	public static byte[] serialize(Object object) {
		ObjectOutputStream objectOutputStream;
		ByteArrayOutputStream byteArrayOutputStream;
		try {
			// 序列化
			byteArrayOutputStream = new ByteArrayOutputStream();
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(object);
			return byteArrayOutputStream.toByteArray();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 字节流反序列化
	 * @param bytes 字节流
	 * @return Object 对象
	 */
	public static Object unSerialize(byte[] bytes) {
		ByteArrayInputStream byteArrayInputStream;
		try {
			// 反序列化
			byteArrayInputStream = new ByteArrayInputStream(bytes);
			ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
			return objectInputStream.readObject();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
